﻿using SimpleChart.Kernel.Painter;
using SimpleChart.Kernel.Series;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleChart.Kernel
{
    public class Chart
    {
        private int _width;
        private int _height;
        private Image _image;

        public Chart(int width = 800, int height = 600)
        {
            _width = width;
            _height = height;
        }

        public string Title { get; set; }

        public ICollection<SeriesBase> SeriesCollection { get; set; } = new List<SeriesBase>();

        public DataTable Data { get; set; }

        public string AxisXMember { get; set; }

        public Image GetImage()
        {
            if (_image == null)
            {
                _image = Draw();
            }
            return _image;
        }

        private Image Draw()
        {
            Image image = new Bitmap(_width, _height);

            Graphics graphics = Graphics.FromImage(image);
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            DrawChartArea(graphics);
            DrawSeries(graphics);

            return image;
        }

        private void DrawSeries(Graphics graphics)
        {
            foreach (var item in SeriesCollection)
            {
                SeriesPainterBase painter = GetPainter(item);
                painter.Draw(graphics, this, item, _width, _height);
            }
        }

        private void DrawChartArea(Graphics graphics)
        {
            new ChartAreaPainter().Draw(graphics, this, _width, _height);
        }

        private SeriesPainterBase GetPainter(SeriesBase series)
        {
            System.Reflection.MemberInfo info = series.GetType();
            PainterAttribute attribute = Attribute.GetCustomAttribute(info, typeof(PainterAttribute)) as PainterAttribute;
            string painterName = attribute.PainterName;

            Type type = Type.GetType(painterName);
            dynamic obj = type.Assembly.CreateInstance(painterName);
            SeriesPainterBase painter = obj;

            return painter;
        }
    }
}
